#include <vector>
#include <string.h>
#include <stdlib.h>

#include <opencv/cv.h>

#include "yuv420sp2rgb.h"
#include "spice/vspice.h"
#include "VSpice.h"
#include "Recognition.h"
#include "Element.h"
#include "ReadData.h"

#include "log.h"
#include <android/log.h>

#define WIDTHBYTES(bits) (((bits) + 31) / 32 * 4)

using namespace cv;
using namespace std;

void yuvToRGB(unsigned char *yuv, unsigned char *rgb,
		int width, int height, bool grey)
{
	unsigned char *buff;
	unsigned char *out;
	buff = yuv;
	out = rgb;

	if(grey) {
		color_convert_common(buff, buff + width * height, 
				width, height, out, 1);
	}
	else {
		color_convert_common(buff, buff + width * height, 
				width, height, out, 0);
	}
}

int test() 
{
	int ret = 0;
	char strFail[80] = "Vision Spice Failed...";
	char strSuccess[80] = "Vision Spice...";

	char cirfile[30] = "/sdcard/vspice/rc.cir";
	char rawfile[30] = "/sdcard/vspice/rc.raw";
	ret = spice(cirfile, rawfile);
	LOG("spice done.");

	readdata_fromraw(rawfile);
	LOG("read raw data");
	return 0;
}

unsigned char *convert(unsigned char *img, int width, int height)
{
	unsigned char *rgb = NULL;

	rgb = (unsigned char *)malloc(sizeof(unsigned char)
			* width * height * 3);
	LOG("memory allocated");
	yuvToRGB(img, rgb, width, height, false);
	LOG("finish convert yuv -> rgb");

	return rgb;
}

Element *testcv(unsigned char *rgb, int width, int height, int *size)
{
	IplImage *src, *dst;
	IplImage *gray;

	src = cvCreateImageHeader(cvSize(width, height),
			IPL_DEPTH_8U, 3);
	cvSetImageData(src, rgb, WIDTHBYTES(
				640*IPL_DEPTH_8U*3));
	cvFlip(src, NULL, 0);
	src->origin = 0;

	vector<Element> emt = Recognition(src);
	Element *elements = new Element[emt.size()];

	for(int i = 0 ; i < emt.size() ; i++) {
		elements[i] = emt[i];
	}

	cvReleaseImageHeader(&src);

	*size = emt.size();

	return elements;
}

